package com.fowo.api.common.model;

import io.lettuce.core.output.ListOfGenericMapsOutput;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 提供表示列表数据变更的信息
 */
public class ListChanges<T> implements Iterable<ListChanges.Item<T>> {
    private final List<Item<T>> coreList = new ArrayList<>();

    @Override
    public Iterator<Item<T>> iterator() {
        return new ListIterator<T>(this.coreList);
    }

    /**
     * 添加新项
     * @param current 新的项
     * @param shadowId 插入毅的假 ID
     */
    public void addNew(T current, Long shadowId) {
        coreList.add(new Item<>(ItemType.New, null, current, shadowId));
    }

    /**
     * 添加更新项
     * @param old 原始项
     * @param current 更新项
     */
    public void addUpdate(T old, T current) {
        coreList.add(new Item<>(ItemType.Update, old, current, null));
    }

    /**
     * 添加删除项
     * @param old 原始项
     */
    public void addDelete(T old) {
        coreList.add(new Item<>(ItemType.Delete, old, null, null));
    }

    public enum ItemType {
        New, Update, Delete
    }

    @AllArgsConstructor
    @Data
    public static class Item<T> {
        private ItemType type;
        private T old;
        private T current;
        private Long shadowId;
    }

    static class ListIterator<T> implements Iterator<Item<T>>
    {

        private final List<Item<T>> items;
        private int index;

        public ListIterator(List<Item<T>> items) {
            this.items = items;
            this.index = 0;
        }

        @Override
        public boolean hasNext() {
            return index < items.size();
        }

        @Override
        public Item<T> next() {
            return items.get(index++);
        }
    }
}
